<template>
  <div class="emergency-system">
    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="danger" @click="showEditor()" class="create-btn">
        <el-icon class="btn-icon"><AlarmClock /></el-icon>
        新建事件
      </el-button>

      <div class="filters">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索事件..."
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon class="input-icon"><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterStatus"
          placeholder="全部状态"
          clearable
          class="status-select"
        >
          <el-option
            v-for="status in statusOptions"
            :key="status.value"
            :label="status.label"
            :value="status.value"
          />
        </el-select>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="paginatedData"
      v-loading="loading"
      style="width: 100%"
      stripe
      highlight-current-row
      :header-cell-style="{ position: 'sticky', top: '0', zIndex: '10',}"
      height="550"
    >
      <!-- 紧急级别 -->
      <el-table-column prop="level" label="级别" width="90">
        <template #default="{ row }">
          <div class="priority-badge" :class="`level-${row.level}`">
            <span class="dot"></span>
            {{ priorityText[row.level as EmergencyLevel] }}
          </div>
        </template>
      </el-table-column>

      <!-- 事件详情 -->
      <el-table-column prop="title" label="事件详情" min-width="240">
        <template #default="{ row }">
          <div class="event-content">
            <h4 class="event-title">{{ row.title }}</h4>
            <p class="event-desc">{{ truncate(row.description, 45) }}</p>
            <div class="event-meta">
              <time class="event-time">{{ formatTime(row.createdAt) }}</time>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 处理状态 -->
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <div class="status-badge" :class="`status-${row.status}`">
            {{ statusText[row.status as EmergencyStatus] }}
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button
              type="danger"
              size="small"
              @click="toggleStatus(row)"
              class="status-btn"
            >
              {{ row.status === 'processed' ? '重新打开' : '标记处理' }}
            </el-button>

            <el-dropdown trigger="click">
              <el-button type="danger" size="small" class="more-btn">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="showEditor(row)">
                    <el-icon class="dropdown-icon"><Edit /></el-icon>编辑
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click="confirmDelete(row)"
                    class="danger-item"
                  >
                    <el-icon class="dropdown-icon"><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="filteredData.length"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showEditorDialog"
      :title="editingItem ? '编辑事件' : '新建事件'"
      width="600px"
      destroy-on-close
    >
      <el-form :model="editorForm" label-width="80px" ref="formRef">
        <el-form-item label="标题" prop="title" required>
          <el-input v-model="editorForm.title" placeholder="请输入事件标题" />
        </el-form-item>

        <el-form-item label="描述" prop="description" required>
          <el-input
            v-model="editorForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入详细事件描述"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>

        <el-form-item label="级别" prop="level" required>
          <el-select v-model="editorForm.level" placeholder="请选择紧急级别">
            <el-option
              v-for="level in levelOptions"
              :key="level.value"
              :label="level.label"
              :value="level.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="editorForm.status" placeholder="请选择状态">
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showEditorDialog = false">取消</el-button>
        <el-button type="danger" @click="saveItem">确认保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
  AlarmClock,
  Search,
  MoreFilled,
  Edit,
  Delete
} from '@element-plus/icons-vue'

type EmergencyLevel = 'critical' | 'high' | 'medium'
type EmergencyStatus = 'pending' | 'processing' | 'processed'

interface EmergencyItem {
  id: string
  title: string
  description: string
  level: EmergencyLevel
  status: EmergencyStatus
  createdAt: number
  updatedAt: number
}

// 响应式状态
const loading = ref(false)
const searchKeyword = ref('')
const filterStatus = ref<EmergencyStatus | ''>('')
const currentPage = ref(1)
const pageSize = ref(20)
const showEditorDialog = ref(false)
const editingItem = ref<EmergencyItem | null>(null)
const formRef = ref<FormInstance>()
const emergencyData = ref<EmergencyItem[]>([])

const editorForm = reactive<Omit<EmergencyItem, 'id' | 'createdAt' | 'updatedAt'>>({
  title: '',
  description: '',
  level: 'medium',
  status: 'pending'
})

// 常量配置
const levelOptions = [
  { value: 'critical', label: '特急' },
  { value: 'high', label: '紧急' },
  { value: 'medium', label: '一般' }
] as const

const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'processed', label: '已处理' }
] as const

const priorityText: Record<EmergencyLevel, string> = {
  critical: '特急',
  high: '紧急',
  medium: '一般'
}

const statusText: Record<EmergencyStatus, string> = {
  pending: '待处理',
  processing: '处理中',
  processed: '已处理'
}

// 计算属性
const filteredData = computed(() => {
  return emergencyData.value.filter(item => {
    const keywordMatch = item.title.includes(searchKeyword.value) ||
      item.description.includes(searchKeyword.value)
    const statusMatch = filterStatus.value ?
      item.status === filterStatus.value : true
    return keywordMatch && statusMatch
  }).sort((a, b) => b.createdAt - a.createdAt)
})

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredData.value.slice(start, start + pageSize.value)
})

// 生命周期
onMounted(() => {
  loadData()
})

// 数据操作
const STORAGE_KEY = 'emergency-system-data'

function loadData() {
  const data = localStorage.getItem(STORAGE_KEY)
  if (data) {
    try {
      emergencyData.value = JSON.parse(data)
    } catch {
      generateMockData()
    }
  } else {
    generateMockData()
  }
}

function generateMockData() {
  emergencyData.value = Array.from({ length: 50 }, (_, i) => ({
    id: `EMG-${Date.now()}-${i}`,
    title: `失踪人口事件 ${i + 1}`,
    description: `事件描述 ${i + 1} - 失踪者姓名: 张三, 年龄: ${20 + (i % 30)}岁, 失踪时间: ${new Date(Date.now() - i * 3600000).toLocaleString('zh-CN')}, 失踪地点: 北京市某地。`,
    level: ['critical', 'high', 'medium'][i % 3] as EmergencyLevel,
    status: ['pending', 'processing', 'processed'][i % 3] as EmergencyStatus,
    createdAt: Date.now() - i * 3600000,
    updatedAt: Date.now() - i * 3600000
  }))
  saveData()
}

function saveData() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(emergencyData.value))
}

// 业务逻辑
function showEditor(item?: EmergencyItem) {
  if (item) {
    editingItem.value = item
    Object.assign(editorForm, item)
  } else {
    editingItem.value = null
    Object.assign(editorForm, {
      title: '',
      description: '',
      level: 'medium',
      status: 'pending'
    })
  }
  showEditorDialog.value = true
}

async function saveItem() {
  if (!formRef.value) return
  try {
    await formRef.value.validate()

    if (editingItem.value) {
      const index = emergencyData.value.findIndex(i => i.id === editingItem.value!.id)
      emergencyData.value[index] = {
        ...editorForm,
        id: editingItem.value.id,
        createdAt: editingItem.value.createdAt,
        updatedAt: Date.now()
      }
    } else {
      emergencyData.value.unshift({
        ...editorForm,
        id: `EMG-${Date.now()}`,
        createdAt: Date.now(),
        updatedAt: Date.now()
      })
    }

    saveData()
    showEditorDialog.value = false
    ElMessage.success(editingItem.value ? '更新成功' : '创建成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

async function confirmDelete(item: EmergencyItem) {
  try {
    await ElMessageBox.confirm(
      `确定删除事件 "${item.title}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'confirm-delete'
      }
    )
    emergencyData.value = emergencyData.value.filter(i => i.id !== item.id)
    saveData()
    ElMessage.success('删除成功')
  } catch {}
}

function toggleStatus(item: EmergencyItem) {
  const newStatus = item.status === 'processed' ? 'pending' : 'processed'
  const index = emergencyData.value.findIndex(i => i.id === item.id)
  emergencyData.value[index].status = newStatus
  emergencyData.value[index].updatedAt = Date.now()
  saveData()
  ElMessage.success(`已标记为 ${statusText[newStatus as EmergencyStatus]}`)
}

// 工具函数
function formatTime(timestamp: number) {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function truncate(text: string, length: number) {
  return text.length > length ? text.slice(0, length) + '...' : text
}

// 定义 handleSearch 方法
function handleSearch() {
  currentPage.value = 1; // 搜索时重置页码
}
</script>

<style lang="scss" scoped>
.emergency-system {
  padding: 14px 12px;
  width: 95%;
  margin: 0 auto;
  height: 90%;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
  gap: 16px;
  align-items: center;

  .filters {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.create-btn {
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;

  .btn-icon {
    margin-right: 8px;
    font-size: 16px;
  }

  &:hover {
    transform: translateY(-1px);
  }
}

.search-input {
  width: 280px;
}

.status-select {
  width: 140px;
}

.priority-badge {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;

  .dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
  }

  &.level-critical {
    background: #fff0f0;
    color: #ff4d4f;
    .dot { background: #ff4d4f; }
  }

  &.level-high {
    background: #fff3f0;
    color: #ff7d4d;
    .dot { background: #ff7d4d; }
  }

  &.level-medium {
    background: #fff8f0;
    color: #ffa94d;
    .dot { background: #ffa94d; }
  }
}

.status-badge {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;

  &.status-pending {
    background: #fff0f0;
    color: #ff4d4f;
  }

  &.status-processing {
    background: #fffbe6;
    color: #faad14;
  }

  &.status-processed {
    background: #f6ffed;
    color: #52c41a;
  }
}

.event-content {
  .event-title {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
  }

  .event-desc {
    margin: 6px 0;
    font-size: 13px;
    line-height: 1.4;
  }

  .event-meta {
    margin-top: 8px;
    font-size: 12px;
  }
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;

  .status-btn {
    padding: 6px 12px;
    font-size: 12px;
  }

  .more-btn {
    padding: 6px 10px;
  }
}

.pagination-wrap {
  margin-top: 28px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination.is-background) {
  --el-color-primary: #ff4d4f;
}
:deep(.el-input) {
  --el-color-primary: #ff4d4f;
}
:deep(.el-select) {
  --el-color-primary: #ff4d4f;
}
:deep(.el-pagination) {
  --el-color-primary: #ff4d4f;
}

</style>
